<template>
  <el-dialog
      v-model="isShow"
      title="新增字典"
      width="450"
      align-center
    >
      <el-form ref="formRef" :model="form" label-width="100px">
        <el-form-item label="字典编码" prop="type_code" :rules="[{ required: true, message: '此项必填'}]">
          <el-input v-model="form.type_code" @blur="checkCode" />
        </el-form-item>
        <el-form-item label="字典名称" prop="type_name"  :rules="[{ required: true, message: '此项必填'}]">
          <el-input v-model="form.type_name" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" resize="none" :rows="7" />
        </el-form-item>
      </el-form>
      <template #footer>
        <ElButton type="primary" :disabled="!allowSubmit" @click="submit">确认</ElButton>
        <ElButton type="default" @click="isShow = false">取消</ElButton>
      </template>
    </el-dialog>
</template>

<script lang="ts">
import { findByCode, add } from '@/api/dictType'
import { ElNotification } from 'element-plus'
  export default {
    data() {
      return {
        isShow: false,
        allowSubmit: false,
        form: {
          type_code: '',
          type_name: '',
          remark: ''
        }
      }
    },
    methods: {
      open(data: any) {
        this.isShow = true
      },
      async submit() {
        const formRef = this.$refs.formRef as any
        const res = await formRef.validate()
        if (!res) return
        await add(this.form)
        this.isShow = false;
        this.$emit('upload')
        formRef.resetFields()
        this.allowSubmit = false
      },
      async checkCode() {
        if (!this.form.type_code) return
        const res = await findByCode({ type_code: this.form.type_code })
        this.allowSubmit = res.data === null
        if (!this.allowSubmit) {
          ElNotification({
            title: '警告',
            message: '字典编码已存在，请尝试其他编码！',
            type: 'warning',
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>